package com.pactera.asmp.server.common.exception.handler;

import com.pactera.asmp.server.common.constants.ResultCode;
import com.pactera.asmp.server.common.exception.CustomException;
import com.pactera.asmp.server.common.exception.GenericError;
import com.pactera.asmp.server.common.exception.GenericException;
import com.pactera.asmp.server.common.logprint.utils.StringUtils;
import com.pactera.asmp.server.entity.ResponseResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: tlsserver
 * @Package com.pactera.asmp.server.common.exception.handler
 * @ClassName: GlobalExceptionHandler
 * @Description: 全局异常捕获
 * @Date 2020/06/01 10:57
 * @Author lvzhiqiang
 * @Version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(CustomException.class)
    public ResponseResult handleException(CustomException e) {
        // 打印异常信息
        log.error("### 异常信息:{} ###", e.getMessage());
        return new ResponseResult(e.getResultCode());
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(GenericException.class)
    public ResponseResult genericException(GenericException e) {
        log.error(e.getMessage(), e);
        GenericError genericError = e.getGenericError();
        return ResponseResult.defaultFail(genericError.getCode(),e.getMessage());
    }
    /**
     * 参数错误异常
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public ResponseResult handleException(Exception e) {

        StringBuilder errorMsg = new StringBuilder();
        List<String> msgList = new ArrayList<>();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException validException = (MethodArgumentNotValidException) e;
            BindingResult result = validException.getBindingResult();
            if (result.hasErrors()) {
                List<ObjectError> errors = result.getAllErrors();
                errors.forEach(p ->{
                    FieldError fieldError = (FieldError) p;
                    if(!msgList.contains(fieldError.getDefaultMessage())){
                        msgList.add(fieldError.getDefaultMessage());
                        if(errorMsg.length() > 0){
                            errorMsg.append(", ");
                        }
                        errorMsg.append(fieldError.getDefaultMessage());
                    }
                    log.error("### 请求参数错误：{},field:{},errorMessage:{}",fieldError.getObjectName(),fieldError.getField(),fieldError.getDefaultMessage());
                });
            }
        } else if (e instanceof BindException) {
            BindException bindException = (BindException)e;
            if (bindException.hasErrors()) {
                log.error("### 请求参数错误: {}", bindException.getAllErrors());
            }
        }

        return new ResponseResult(ResultCode.PARAM_IS_INVALID.code()
                , StringUtils.isEmpty(errorMsg.toString())?ResultCode.PARAM_IS_INVALID.message():errorMsg.toString(),null);
    }

    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult handleOtherException(Exception e){
        //打印异常堆栈信息
//        e.printStackTrace();
        // 打印异常信息
        log.error("### 不可知的异常:{} ###", e.getMessage());
        return new ResponseResult(ResultCode.SYSTEM_INNER_ERROR.code(), ResultCode.SYSTEM_INNER_ERROR.message() + e.getMessage(), null);
    }

    /**
     * 处理 UnauthorizedException 的异常
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseResult handleNoPermissionException(UnauthorizedException e){
        //打印异常堆栈信息
//        e.printStackTrace();
        // 打印异常信息
        log.error("### UnauthorizedException 异常:{} ###", e.getMessage());
        return new ResponseResult(ResultCode.BUSINESS_NO_PERMISSION.code(), ResultCode.BUSINESS_NO_PERMISSION.message() + e.getMessage(), null);
    }
}
